"""
登录页面模块
"""

import customtkinter as ctk
import tkinter as tk
from tkinter import messagebox
from typing import Callable, Optional
from ..themes import ModernTheme
from ..components import ModernButton, ModernCard
from ..auth_manager import auth_manager
import hashlib
import json
import os
from pathlib import Path


class LoginPage(ctk.CTkFrame):
    """登录页面类"""
    
    def __init__(self, parent, on_login_success: Optional[Callable] = None):
        super().__init__(parent, fg_color="transparent")

        self.on_login_success = on_login_success
        self.users_file = Path("data/users.json")

        # 确保数据目录存在
        self.users_file.parent.mkdir(exist_ok=True)

        # 初始化用户数据
        self.init_users_data()

        self.create_page()

        # 加载记住的用户
        self.load_remembered_users()
    
    def init_users_data(self):
        """初始化用户数据"""
        if not self.users_file.exists():
            # 创建默认管理员账户
            default_users = {
                "admin": {
                    "password": self.hash_password("admin123"),
                    "role": "admin",
                    "name": "管理员",
                    "created_at": "2024-01-01",
                    "last_login": None
                }
            }
            self.save_users_data(default_users)
    
    def hash_password(self, password: str) -> str:
        """密码哈希"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def load_users_data(self) -> dict:
        """加载用户数据"""
        try:
            with open(self.users_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            return {}
    
    def save_users_data(self, users_data: dict):
        """保存用户数据"""
        try:
            with open(self.users_file, 'w', encoding='utf-8') as f:
                json.dump(users_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存用户数据失败: {e}")
    
    def create_page(self):
        """创建登录页面"""
        # 主容器 - 使用grid布局实现完美居中
        main_container = ctk.CTkFrame(self, fg_color="transparent")
        main_container.pack(fill="both", expand=True)

        # 配置grid权重，使内容居中
        main_container.grid_rowconfigure(0, weight=1)
        main_container.grid_rowconfigure(1, weight=0)
        main_container.grid_rowconfigure(2, weight=1)
        main_container.grid_columnconfigure(0, weight=1)
        main_container.grid_columnconfigure(1, weight=0, minsize=750)  # 设置最小宽度
        main_container.grid_columnconfigure(2, weight=1)

        # 登录卡片 - 放在grid中心
        self.login_card = ModernCard(
            main_container,
            title="🔐 用户登录",
            width=750,
            height=520
        )
        self.login_card.grid(row=1, column=1, padx=20, pady=20, sticky="nsew")
        
        # Logo区域
        self.create_logo_section()
        
        # 登录表单
        self.create_login_form()
        
        # 登录按钮
        self.create_login_buttons()
        
        # 底部信息
        self.create_footer_info()

        # 设置焦点到用户名输入框
        self.after(200, self.set_focus_to_username)
    
    def create_logo_section(self):
        """创建Logo区域"""
        logo_frame = ctk.CTkFrame(self.login_card.content_frame, fg_color="transparent")
        logo_frame.pack(pady=(20, 30))
        
        # 应用Logo
        logo_label = ctk.CTkLabel(
            logo_frame,
            text="🎬",
            font=ctk.CTkFont(size=48),
            text_color=ModernTheme.COLORS['primary']
        )
        logo_label.pack()
        
        # 应用名称
        app_name = ctk.CTkLabel(
            logo_frame,
            text="MixVideo",
            font=ModernTheme.get_font('heading_lg'),
            text_color=ModernTheme.get_color('text_primary')
        )
        app_name.pack(pady=(10, 0))
        
        # 副标题
        subtitle = ctk.CTkLabel(
            logo_frame,
            text="智能视频制作平台",
            font=ModernTheme.get_font('body_sm'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        subtitle.pack(pady=(5, 0))
    
    def create_login_form(self):
        """创建登录表单"""
        form_frame = ctk.CTkFrame(self.login_card.content_frame, fg_color="transparent")
        form_frame.pack(fill="x", padx=20, pady=(0, 20))
        
        # 用户名输入
        username_label = ctk.CTkLabel(
            form_frame,
            text="用户名",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_primary'),
            anchor="w"
        )
        username_label.pack(fill="x", pady=(0, 5))
        
        # 使用下拉框支持记住的用户
        self.username_entry = ctk.CTkComboBox(
            form_frame,
            height=40,
            font=ModernTheme.get_font('body'),
            corner_radius=8,
            command=self.on_username_selected,
            values=[]
        )
        self.username_entry.set("请输入用户名")
        self.username_entry.pack(fill="x", pady=(0, 15))

        # 确保输入框可以接收键盘事件
        self.username_entry.bind("<FocusIn>", self.on_username_focus)
        self.username_entry.bind("<KeyPress>", self.on_key_press)
        
        # 密码输入
        password_label = ctk.CTkLabel(
            form_frame,
            text="密码",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_primary'),
            anchor="w"
        )
        password_label.pack(fill="x", pady=(0, 5))
        
        self.password_entry = ctk.CTkEntry(
            form_frame,
            placeholder_text="请输入密码",
            show="*",
            height=40,
            font=ModernTheme.get_font('body'),
            corner_radius=8,
            state="normal"
        )
        self.password_entry.pack(fill="x", pady=(0, 10))
        
        # 记住密码选项
        remember_frame = ctk.CTkFrame(form_frame, fg_color="transparent")
        remember_frame.pack(fill="x", pady=(0, 20))
        
        self.remember_var = ctk.BooleanVar()
        self.remember_checkbox = ctk.CTkCheckBox(
            remember_frame,
            text="保持登录状态",
            variable=self.remember_var,
            font=ModernTheme.get_font('body_sm'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        self.remember_checkbox.pack(side="left")
        
        # 忘记密码链接
        forgot_link = ctk.CTkLabel(
            remember_frame,
            text="忘记密码？",
            font=ModernTheme.get_font('body_sm'),
            text_color=ModernTheme.COLORS['primary'],
            cursor="hand2"
        )
        forgot_link.pack(side="right")
        forgot_link.bind("<Button-1>", self.on_forgot_password)
    
    def create_login_buttons(self):
        """创建登录按钮"""
        button_frame = ctk.CTkFrame(self.login_card.content_frame, fg_color="transparent")
        button_frame.pack(fill="x", padx=20, pady=(0, 20))
        
        # 登录按钮
        self.login_btn = ModernButton(
            button_frame,
            text="🔑 登录",
            variant="primary",
            command=self.on_login,
            height=45
        )
        self.login_btn.pack(fill="x", pady=(0, 10))
        
        # 注册按钮
        self.register_btn = ModernButton(
            button_frame,
            text="📝 注册新账户",
            variant="secondary",
            command=self.on_register,
            height=40
        )
        self.register_btn.pack(fill="x")
        
        # 绑定回车键
        self.username_entry.bind("<Return>", lambda e: self.password_entry.focus())
        self.password_entry.bind("<Return>", lambda e: self.on_login())

        # 绑定点击事件确保焦点
        self.username_entry.bind("<Button-1>", lambda e: self.username_entry.focus())
        self.password_entry.bind("<Button-1>", lambda e: self.password_entry.focus())
    
    def create_footer_info(self):
        """创建底部信息"""
        footer_frame = ctk.CTkFrame(self.login_card.content_frame, fg_color="transparent")
        footer_frame.pack(fill="x", padx=20, pady=(0, 20))
        
        # 默认账户提示
        info_text = ctk.CTkLabel(
            footer_frame,
            text="默认账户: admin / admin123",
            font=ModernTheme.get_font('body_sm'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        info_text.pack()
        
        # 版本信息
        version_text = ctk.CTkLabel(
            footer_frame,
            text="Version 1.0.0",
            font=ModernTheme.get_font('body_sm'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        version_text.pack(pady=(10, 0))

    def set_focus_to_username(self):
        """设置焦点到用户名输入框"""
        try:
            self.username_entry.focus()
            self.username_entry.focus_set()
        except Exception as e:
            print(f"设置焦点失败: {e}")

    def on_username_focus(self, event):
        """用户名输入框获得焦点"""
        pass

    def on_key_press(self, event):
        """键盘按键事件"""
        pass

    def on_login(self):
        """处理登录"""
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()
        remember_me = self.remember_var.get()

        if not username or not password:
            messagebox.showerror("错误", "请输入用户名和密码")
            return

        # 使用认证管理器进行验证
        if auth_manager.authenticate(username, password, remember_me):
            # 登录成功
            user_data = auth_manager.get_current_user()
            self.on_login_success_handler(username, user_data)
        else:
            # 登录失败
            messagebox.showerror("登录失败", "用户名或密码错误")
            self.password_entry.delete(0, 'end')
    
    def on_login_success_handler(self, username: str, user_data: dict):
        """登录成功处理"""
        # 显示欢迎消息
        messagebox.showinfo("登录成功", f"欢迎回来，{user_data.get('name', username)}！")

        # 调用成功回调
        if self.on_login_success:
            self.on_login_success(username, user_data)
    
    def on_register(self):
        """处理注册"""
        messagebox.showinfo("注册", "注册功能开发中...")
    
    def on_forgot_password(self, event):
        """处理忘记密码"""
        messagebox.showinfo("忘记密码", "请联系管理员重置密码")

    def load_remembered_users(self):
        """加载记住的用户"""
        try:
            remembered_users = auth_manager.get_remembered_users()
            if remembered_users:
                self.username_entry.configure(values=remembered_users)
                # 如果只有一个记住的用户，自动填入
                if len(remembered_users) == 1:
                    self.username_entry.set(remembered_users[0])
        except Exception as e:
            print(f"加载记住的用户失败: {e}")

    def on_username_selected(self, username):
        """用户名选择回调"""
        if username and username != "请输入用户名":
            # 自动勾选保持登录状态
            self.remember_var.set(True)
            # 焦点移到密码框
            self.password_entry.focus()

    def load_remembered_users(self):
        """加载记住的用户"""
        try:
            remembered_users = auth_manager.get_remembered_users()
            if remembered_users:
                self.username_entry.configure(values=remembered_users)
                # 如果只有一个记住的用户，自动填入
                if len(remembered_users) == 1:
                    self.username_entry.set(remembered_users[0])
        except Exception as e:
            print(f"加载记住的用户失败: {e}")

    def on_username_selected(self, username):
        """用户名选择回调"""
        if username:
            # 自动勾选保持登录状态
            self.remember_var.set(True)
            # 焦点移到密码框
            self.password_entry.focus()
